<template>
  <div>
    <h3>地址管理</h3>
    <van-address-list
      v-show="!isAdd"
      v-model="chosenAddressId"
      :list="list"
      default-tag-text="默认"
      @add="onAdd"
      @edit="onEdit"
    />
    <button v-show="isConfirm" @click="back">确定</button>

    <van-address-edit
      v-show="isAdd"
      :area-list="areaList"
      show-postal
      show-delete
      show-set-default
      :area-columns-placeholder="['请选择', '请选择', '请选择']"
      @save="onSave"
      @delete="onDelete"
    />
  </div>
</template>

<script>
import { changeNav } from "@/mixins/changenav";
import { areaList } from "@vant/area-data";
import  {mapGetters,mapMutations} from  "vuex"
import {
  myaddressAdd,
  myaddressQuery,
  myaddressUpdate,
} from "@/model/myAddress";
export default {
  mixins: [changeNav],
  beforeRouteEnter(to,from,next){

    next(vm=>{
        if(from.name=="pay"){
            vm.isConfirm = true;
        }

    });
  },
  data() {
    return {
      isConfirm:false,  
      isAdd: false,
      areaList,
      list: [
        //地址列表
      ],
    };
  },
  computed: {
    ...mapGetters("myaddressStore",["defaultChooseId"]),
    chosenAddressId:{
        set(id){
           this.setChooseId(id);
        },
        get(){
            return  this.defaultChooseId;
        }
    },
  },
  async created() {
    let res = await myaddressQuery({
      userid: this.userid,
    });
    this.list = res.data.map((item) => {
      item.address =
        item.province + item.city + item.county + item.addressDetail;
      return item;
    });
  },
  methods: {
    ...mapMutations("myaddressStore",["setChooseId"]),
    back(){
        this.$router.back();
    },
    onAdd() {
      this.isAdd = true;
    },
    onEdit(item, index) {
      this.$toast("编辑地址:" + index);
    },
    async onSave(content) {
      if (content.isDefault) {
        //检查用户是否已经有了默认地址
        let res2 = await myaddressQuery({
          userid: this.userid,
          isDefault: true,
        });
        if (res2.data.length) {
          //有
          let existInfo = res2.data[0];
          await myaddressUpdate(existInfo.id, {
            isDefault: false,
          }); //更新数据库
          this.list.filter(
            (item) => item.id == existInfo.id
          )[0].isDefault = false; //更新页面效果
        }
      }

      //地址的新增
      let res = await myaddressAdd({ ...content, userid: this.userid });
      let item = res.data;
      this.list.push({
        ...item,
        address: item.province + item.city + item.county + item.addressDetail,
      });
      this.isAdd = false;
    },
    onDelete() {
      this.$toast("delete");
    },
  },
};
</script>

<style></style>
